//添加购物车

$(function () {
  //从路径里面获取由首页点击进入详情页的商品id
  function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
      var pair = vars[i].split("=");
      if (pair[0] == variable) {
        return pair[1];
      }
    }
    return false;
  }
  var a = Number(getQueryVariable("pid"));

  axios
    .get("http://jx.xuzhixiang.top/ap/api/detail.php", { params: { id: a } })
    .then(function (res) {
      console.log(res);
      var str = "";
      str = `
    <div id="zoomBox">
        <div id="midArea">
          <img src="${res.data.data.pimg}" />
          <div id="zoom"></div>
        </div>
        <div id="bigArea">
          <img src="${res.data.data.pimg}" />
        </div>
        <div id="smallArea">
          <img src="${res.data.data.pimg}" />
          <img src="${res.data.data.pimg}" />
        </div>
      </div> 
      <!-- 放大镜结束 -->
      <div class="detail_mess">
        <h3>${res.data.data.pdesc}</h3>
        <div class="pirce">￥${res.data.data.pprice}</div>
        <div class="yunfei">全部享受包邮</div>
        <div class="number">
          <span class="plus">+</span>
          <span class="num">1</span>
          <span class="substract">-</span>
        </div>
        <div class="d_cart">
          <div class="car">加入购物车</div>
        </div>
      </div>    
    `;
      $(".detail_con").append(str);

      //添加或者减少商品
    })
    .then(function () {
      var n = 1;
      $(".plus").on("click", function () {
        n++;
        $(".num").text(n);
      });
      $(".substract").on("click", function () {
        if (n <= 1) {
          return;
        }
        n--;
        $(".num").text(n);
      });

      //添加购物车
      var uid = 74651;
      $(".car").on("click", function () {
        //console.log(n)
        axios
          .get("http://jx.xuzhixiang.top/ap/api/add-product.php", {
            params: { uid, pid: a, pnum: n },
          })
          .then(function (res) {
            location.href = `car.html?pid=${a}&&uid=${74651}&&pnum=${n}`;
          });
      });
      //放大镜
      console.log($("#midArea"));
      $("#midArea>img").on("mousemove", function (e) {
        $("#bigArea,#zoom").show();
        var x = e.offsetX - 100;
        var y = e.offsetY - 100;
        if (x <= 0) {
          x = 0;
        }
        if (x >= 200) {
          x = 200;
        }
        if (y <= 0) {
          y = 0;
        }
        if (y >= 200) {
          y = 200;
        }
        console.log(x, y);
        $("#zoom").css({ top: y, left: x });
        $("#bigArea>img").css({ top: -y * 2, left: -x * 2 });
      });
      /* $("#midArea>img").on("mouseout", function (e) {
        $("#bigArea,#zoom").hide();
      }); */
      $("#midArea").mouseout(function () {
        $("#bigArea,#zoom").hide();
      });
    });
});
